//  IDVI 1.0 source copyright 1996 Garth A. Dickie
//
//  This source is free for non-commercial use.  No warranty, etc.
//  Please acknowledge reuse by including the line:
//
//  "Based in part on IDVI 1.0 source copyright 1996 Garth A. Dickie"
//
//  in your documentation and source code.  For commercial use or
//  distribution, please contact the author.  Please also send
//  questions, comments, bug reports, or fixes.
//
//  Best Regards,
//  Garth A. Dickie
//  dickie@elastic.avid.com

package ibook.v10.idvi.display;

import java.awt.Image;
import java.awt.Graphics;
import java.util.Hashtable;

//  This is a featherweight class in the View heierarchy.
//
//  There is at most one instance of the CharacterView class for each
//  triple (DVICharacter, ColorScheme, scale).  This is implemented as at
//  most one CharacterView for each pair (ScaledCharacter, ScaledColorScheme),
//  at most one ScaledCharacter for each pair (DVICharacter, scale), and
//  at most one ScaledColorScheme for each pair (ColorScheme, scale).

class CharacterView extends View {
    private static CharacterView    key = new CharacterView( );
    private static Hashtable        cache = new Hashtable( );

    static synchronized CharacterView getCharacterView(
            ScaledCharacter scaledCharacter, ScaledColorScheme colorScheme ) {

        key.scaledCharacter = scaledCharacter;
        key.colorScheme = colorScheme;

        CharacterView result = ( CharacterView ) cache.get( key );

        if( result == null ) {
            result = key;
            cache.put( key, result );
            key = new CharacterView( );

            result.init( );
        }

        return result;
    }




    private ScaledCharacter     scaledCharacter;
    private ScaledColorScheme   colorScheme;
    private Image[ ]            image;

    private CharacterView( ) {
    }

    private void init( ) {
        image = new Image[ ScaledColorScheme.kIndexCount ];
    }




    int getBounds( DVIRectangle bounds, int scale, int x, int y, Block block ) {
        scaledCharacter.getBounds( bounds, x, y );
        return 0;
    }

    void paint( Graphics g, int color, DVIRectangle bounds, DVIRectangle clip, int yOffset ) {
        if( image[ color ] == null )
            prepareImage( color );
        
        g.drawImage( image[ color ], bounds.left, bounds.top, null );
    }

    private synchronized void prepareImage( int color ) {
        if( image[ color ] == null )
            image[ color ] = scaledCharacter.getImage( colorScheme, color );
    }




    public int hashCode( ) {
        return scaledCharacter.hashCode( ) ^ ( colorScheme.hashCode( ) << 16 );
    }

    public boolean equals( Object object ) {
        return object instanceof CharacterView && equals(( CharacterView ) object );
    }

    public boolean equals( CharacterView key ) {
        return key.scaledCharacter == scaledCharacter && key.colorScheme == colorScheme;
    }
}
